﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.IO;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web;

namespace MvcControlsToolkit
{
    public class Tabs: Control
    {
        public string OnSelected
        {
            get { return Attributes["select"]; }
            set { Attributes["select"] = value; }
        }

        public bool IsCached
        {
            get
            {
                if (Attributes.ContainsKey("cache"))
                    return bool.Parse(Attributes["cache"]);
                else return false;
            }
            set { Attributes["cache"] = value.ToString().ToLower(); }
        }

        public bool IsCollapsible
        {
            get
            {
                if (Attributes.ContainsKey("collapsible"))
                    return bool.Parse(Attributes["collapsible"]);
                else return false;
            }
            set { Attributes["collapsible"] = value.ToString().ToLower(); }
        }

        public string EventName
        {
            get { return GetString("event"); }
            set { SetString("event", value); }
        }

        public string Spinner
        {
            get { return GetString("spinner"); }
            set { SetString("spinner", value); }
        }

        public string AdditionalAttributes { get; set; }
        public string ContainerCss { get; set; }
        public List<TabItem> TabItems{get;set;}

        public Tabs(string name): base(name)
        {
            this.TabItems = new List<TabItem>();
            //this.Spinner = "Loading...";
        }

        /// <summary>
        /// Add a tab
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public Tabs AddTab(TabItem item)
        {
            TabItems.Add(item); 
            return this;
        }

        public override string GetJScript()
        {
            var result = new StringBuilder();

            foreach (string key in Attributes.Keys)
            {
                result.AppendFormat(", {0}: {1}", key, Attributes[key]);
            }

            /* Disable Tabs */
            var selectedIndex = getSelectedTab();
                result.Append(", selected: " + selectedIndex);

            /* Disable Tabs */
            var disabledIndexes = getDisabledList();
            if (!string.IsNullOrEmpty(disabledIndexes))
                result.Append(", disabled: " + disabledIndexes);

            if (result.Length > 0)
                result.Remove(0, 1);

            return "var "+Name+" = $(\"#"+Name+ "\").tabs({"+result+"});";
        }

        public override string GetHtml()
        {
            var result = new StringBuilder();
            var css = String.Empty;
            var index = 0;
            var partialViews = new StringBuilder();

            if (!string.IsNullOrEmpty(this.ContainerCss)) css = "class=\"" + this.ContainerCss + "\"";

            foreach (TabItem item in this.TabItems)
            {
                string tabContent = String.Empty;

                switch (item.ContentType)
                {
                    case ContentType.Static:
                        tabContent = item.HTMLContent;
                        item.Action = "#tabItem_" + index;
                        break;
                    case ContentType.PartialView:
                        item.Action = "#tabItem_" + index;
                        tabContent = ControlManager.RenderPartialToString(Helper, item.PartialViewName, item.PartialViewModel, item.PartialViewData);
                        break;
                    case ContentType.RemoteAction:                        
                        break;
                }

                if (item.ContentType != ContentType.RemoteAction)
                    partialViews.Append("<div id=\"tabItem_" + index + "\">" + tabContent + "</div>");

                result.Append(item);

                index++;
            }
            return string.Format("<div id=\"{0}\" {1}><ul>{2}</ul>{3}</div>", this.Name, css, result.ToString(), partialViews.ToString());
        }

        private string getDisabledList()
        {
            var result = new List<int>();
            for (int i = 0; i < this.TabItems.Count; i++)
                if (!TabItems[i].Enabled)
                    result.Add(i);

            if (result.Count != 0)
            {
                var serializer = new JavaScriptSerializer();

                return serializer.Serialize(result.ToArray());
            }
            return
                null;
        }

        private int getSelectedTab()
        {
            for (int i = 0; i < this.TabItems.Count; i++)
                if (this.TabItems[i].Selected)
                    return i;

            return 0;
        }
    }
}
